<?php
/**
 * 考勤操作控制器
 */

namespace app\admin\controller;

use app\common\model\Staff;
use PhpOffice\PhpSpreadsheet\IOFactory;
use think\Db;
use think\facade\Env;
use think\Request;
use app\common\model\Attendance;
use app\common\model\Department;
use app\common\validate\AttendanceValidate;

class AttendanceController extends Controller
{

    //列表
    public function index(Request $request, Attendance $model)
    {
        $param = $request->param();
        $where1 = [];
        if (!empty($param['attendance_time']) ) {
            $where1['attendance_time'] = strtotime($param['attendance_time']);
        }
        $where = [];
        if (!empty($param['staff_id'])){
            $where['id']=$param['staff_id'];
        }

        if (!empty($param['department_id'])) {
            $where['department_id']=$param['department_id'];
        }
        $order = $param['_order'] ?? '';
        $by    = $param['_by'] ?? '';
        $model = $model->hasWhere('staff',$where)->with(['staff'=>function($query){
            $query->with(['department','insure']);
        }])->where($where1)->order($order ?: '', $by ?: '')->order('department_id','DESC');

        if (isset($param['export_data']) && $param['export_data'] == 1) {
            $header = ['员工ID', '部门ID', '员工', '部门', '市场员工职级', '考勤时间', '病假时间（时）', '事假时间（时）', '旷工时间（时）', '出差时间（天）', '日常存班时间（小时）', '会议存班时间（时）', '是否全勤(全勤1，不全勤0)', '出勤天数', '迟到次数', '迟到情况（多次用英文逗号隔开）', '补卡次数', '缺卡次数', '市场缺卡扣款', '市场缺签卡次数', '市场缺签卡扣款', '备注'];
            $body = [];
            $data = $model->select();
            foreach ($data as $item) {
                $record = [];
                $record['staff_id'] = $item->staff_id;
                $record['department_id'] = $item->staff->department_id;
                $record['staff_name'] = $item->staff->name;
                $record['department_name'] = $item->staff->department->name;
                $record['position_level'] = $item->position_level;
                $record['attendance_time'] = $item->attendance_time;
                $record['sick_leave'] = $item->sick_leave;
                $record['absence_leave'] = $item->absence_leave;
                $record['absenteeism'] = $item->absenteeism;
                $record['business_travel'] = $item->business_travel;
                $record['storage_time'] = $item->storage_time;
                $record['storage_meeting_time'] = $item->storage_meeting_time;
                $record['is_full'] = $item->is_full;
                $record['attendance_days'] = $item->attendance_days;
                $record['late_times'] = $item->late_times;
                $late = $item->late_time;
                $record['late_time'] = '';
                if ($late) {
                    foreach ($late as $k => $v) {
                        $record['late_time'] .= $v . ',';
                    }
                    if ($record['late_time']) {
                        substr($record['late_times'], -1, 1);
                    }
                }
                $record['repair_card_times'] = $item->repair_card_times;
                $record['miss_card_times'] = $item->miss_card_times;
                $record['miss_card_cut'] = $item->miss_card_cut;
                $record['miss_sign_times'] = $item->miss_sign_times;
                $record['miss_sign_cut'] = $item->miss_sign_cut;
                $record['remarks'] = $item->remarks;
                $body[] = $record;
            }

            return $this->exportData($header, $body, '考勤-' . date('Y-m-d-H-i-s'));
        }

        $data = $model->paginate($this->admin['per_page'], false, ['query' => $request->get()]);
        if (isset($param['department_id']) && !empty($param['department_id']) && Department::get($param['department_id'])) {

            $this->assign('department_list', $this->getSelectList(Department::get($param['department_id']), $param['department_id']));
        } else {
            $this->assign('department_list', $this->getSelectList(new Department));
        }
        //关键词，排序等赋值
        $this->assign($request->get());
        $this->assign([
            'staff_list' => Staff::all(),
            'data' => $data,
            'page' => $data->render(),
            'total' => $data->total(),
        ]);
        return $this->fetch();
    }

    //excel导入入库
    public function importData(Request $request, Attendance $attendance)
    {
        ini_set('max_execution_time','0');
        $params = $request->param();
        $attendance_data = [];
        if (isset($params['attendance_time'])) {
            $attendance_time = strtotime($params['attendance_time']);
            $attendance_data = Attendance::where('attendance_time', $attendance_time)->column('staff_id', 'id');
        } else {
            return json_encode(['code' => 0, 'msg' => '请先选择时间']);

        }
        //获取表格的大小，限制上传表格的大小5M

        $file_size = $_FILES['attendance']['size'];
        if ($file_size > 30 * 1024 * 1024) {
            $this->error('文件大小不能超过30M');
            exit();
        }

        //限制上传表格类型
        $fileExtendName = substr(strrchr($_FILES['attendance']["name"], '.'), 1);
        //application/vnd.ms-excel  为xls文件类型
        if ($fileExtendName != 'xlsx' && $fileExtendName != 'xls') {
            $this->error('表格必须为xlsx或xls格式！');
            exit();
        }
        $header1 = ['员工ID', '部门ID', '员工', '部门', '市场员工职级', '考勤时间', '病假时间（时）', '事假时间（时）', '旷工时间（时）', '出差时间（天）', '日常存班时间（小时）', '会议存班时间（时）', '是否全勤(全勤1，不全勤0)', '出勤天数', '迟到次数', '迟到情况（多次用英文逗号隔开）', '补卡次数', '缺卡次数', '市场缺卡扣款', '市场缺签卡次数', '市场缺签卡扣款', '备注', '状态(启用1,禁用0)',];
        $header = ['staff_id', 'department_id', 'staff_name', 'department_name', 'position_level', 'attendance_time', 'sick_leave', 'absence_leave', 'absenteeism', 'business_travel', 'storage_time', 'storage_meeting_time', 'is_full', 'attendance_days', 'late_times', 'late_time', 'repair_card_times', 'miss_card_times', 'miss_card_cut', 'miss_sign_times', 'miss_sign_cut', 'remarks', 'status'];
        if (is_uploaded_file($_FILES['attendance']['tmp_name'])) {
            // 有Xls和Xlsx格式两种
            if ($fileExtendName === 'xlsx') {
                $objReader = IOFactory::createReader('Xlsx');
            } else {
                $objReader = IOFactory::createReader('Xls');
            }
            $spreadsheet = $objReader->load($_FILES['attendance']['tmp_name']);
            $sheetData = $spreadsheet->getActiveSheet()->ToArray();
            $datas = [];
            $header2 = $sheetData[0];
            if ($header2 !== $header1) {
                return json_encode(['code' => 0, 'msg' => '表格格式不正确']);
            }
            $msg = '';
            foreach ($sheetData as $key => $value) {
                if ($key > 0) {
                    foreach ($value as $k => $v) {
                        if ($header[$k] === 'attendance_time' && strtotime($v) != $attendance_time) {
                            $msg .= $value[2]." : 时间格式不正确<br>";
                            unset($datas[$key]);
                            break;
                        }
                        if ($header[$k] === 'staff_id' && in_array($v, $attendance_data)) {
                            $datas[$key]['id'] = array_search($v, $attendance_data);
                        }
                        if ($header[$k] === 'late_time' && isset($v) && $v != '') {
                            $datas[$key]['late_time'] = json_encode(explode(',', $v));
                        } else {
                            $datas[$key][$header[$k]] = $v ?? '';
                        }
                    }
                }
            }

            Db::startTrans();
            try {
                $attendance->saveAll($datas);
                Db::commit();
                return json_encode(['code' => 1, 'msg' => $msg]);

            } catch (\Exception $e) {
                Db::rollback();
            }

        } else {
            return json_encode(['code' => 0, 'msg' => $_FILES['attendance']['name'] . '文件上传失败 ']);
        }
    }

    //添加
    public function add(Request $request, Attendance $model, AttendanceValidate $validate)
    {
        if ($request->isPost()) {
            $param = $request->param();

            foreach ($param as $key => &$value) {
                if ($key === 'late_time' && !empty($value)) {
                    $param[$key] = json_encode($value, JSON_UNESCAPED_UNICODE);
                }
            }

            //处理附件上传
            if (!empty($_FILES['file']['name'][0])) {
                $attachment_file = new \app\common\model\Attachment;
                $file = $attachment_file->uploadMulti('file');
                if ($file) {
                    $param['file'] = $file;
                } else {
                    return error($attachment_file->getError());
                }
            }

            $validate_result = $validate->scene('add')->check($param);
            if (!$validate_result) {
                return error($validate->getError());
            }

            $result = $model::create($param);

            $url = URL_BACK;
            if (isset($param['_create']) && $param['_create'] == 1) {
                $url = URL_RELOAD;
            }

            return $result ? success('添加成功', $url) : error();
        }
        $miss_card_cut = config('companyRules.miss_card_cut');
        $miss_sign_cut = config('companyRules.miss_sign_cut');
        $data['miss_card_cut'] = $miss_card_cut;
        $data['miss_sign_cut'] = $miss_sign_cut;
        $this->assign([
            'data' => $data,
            'department_list' => $this->getSelectList(new Department),
            'staff_list' => Staff::all(),
        ]);

        return $this->fetch();
    }

    //修改
    public function edit($id, Request $request, Attendance $model, AttendanceValidate $validate)
    {

        $data = $model::where('id', $id)->with('staff')->find();
        if ($request->isPost()) {
            $param = $request->param();

            foreach ($param as $key => &$value) {
                if ($key === 'late_time' && !empty($value)) {
                    $param[$key] = json_encode($value, JSON_UNESCAPED_UNICODE);
                }
            }
            //处理附件上传
            if (!empty($_FILES['file']['name'][0])) {
                $attachment_file = new \app\common\model\Attachment;
                $file = $attachment_file->uploadMulti('file');
                if ($file) {
                    $param['file'] = $file;
                } else {
                    return error($attachment_file->getError());
                }
            }
            $validate_result = $validate->scene('edit')->check($param);
            if (!$validate_result) {
                return error($validate->getError());
            }
            $result = $data->save($param);
            return $result ? success() : error();
        }
        if ($data->staff->department){
            $this->assign(
                ['department_list' => $this->getSelectList($data->staff->department, $data->staff->department->id)]
            );
        }else{
            $this->assign([
                'department_list' => $this->getSelectList(new Department),
            ]);
        }
        $this->assign([
            'data' => $data,
            'staff_list' => Staff::all(),
        ]);
        return $this->fetch('add');

    }

    //删除
    public function del($id, Attendance $model)
    {
        if (count($model->noDeletionId) > 0) {
            if (is_array($id)) {
                if (array_intersect($model->noDeletionId, $id)) {
                    return error('ID为' . implode(',', $model->noDeletionId) . '的数据无法删除');
                }
            } else if (in_array($id, $model->noDeletionId)) {
                return error('ID为' . $id . '的数据无法删除');
            }
        }

        if ($model->softDelete) {
            $result = $model->whereIn('id', $id)->useSoftDelete('delete_time', time())->delete();
        } else {
            $result = $model->whereIn('id', $id)->delete();
        }

        return $result ? success('操作成功', URL_RELOAD) : error();
    }

    //启用
    public function enable($id, Attendance $model)
    {
        $result = $model->whereIn('id', $id)->update(['status' => 1]);
        return $result ? success('操作成功', URL_RELOAD) : error();
    }


    //禁用
    public function disable($id, Attendance $model)
    {
        $result = $model->whereIn('id', $id)->update(['status' => 0]);
        return $result ? success('操作成功', URL_RELOAD) : error();
    }


    //新建用户绩效按月排除重复
    public function nameUnique(Request $request, Attendance $attendance)
    {
        $params = $request->param();
        if (isset($params['attendance_time'])) {
            $params['attendance_time'] = strtotime($params['attendance_time']);
            $params['staff_id'] = intval($params['staff_id']);
        }
        $count = $attendance->where($params)->count();
        if ($count > 0) {
            return error('您的名称重复，请重新输入');
        } else {
            return success('细项可用');
        }
    }

    //工资规章设置
    //邮件设置页面
    public function rule(Request $request)
    {
        $sick_leave_allowance_base = config('companyRules.sick_leave_allowance_base');
        $late_times_limit = config('companyRules.late_times_limit');
        $late_rule_time_money = config('companyRules.late_rule_time_money');
        $repair_card_times_limit = config('companyRules.repair_card_times_limit');
        $repair_card_times_hour = config('companyRules.repair_card_times_hour');
        $repair_card_times_max = config('companyRules.repair_card_times_max');
        $in_department = config('companyRules.in_department');
        $out_department = config('companyRules.out_department');
        $miss_card_cut = config('companyRules.miss_card_cut');
        $miss_sign_cut = config('companyRules.miss_sign_cut');
        $in_miss_card_cut = config('companyRules.in_miss_card_cut');
        $this->assign([
            'sick_leave_allowance_base' => $sick_leave_allowance_base,
            'late_times_limit' => $late_times_limit,
            'late_rule_time_money' => $late_rule_time_money,
            "repair_card_times_limit" => $repair_card_times_limit,
            'repair_card_times_hour' => $repair_card_times_hour,
            'repair_card_times_max' => $repair_card_times_max,
            "in_department" => $in_department,
            'out_department' => $out_department,
            'miss_card_cut' => $miss_card_cut,
            'miss_sign_cut' => $miss_sign_cut,
            'in_miss_card_cut' => $in_miss_card_cut,
        ]);

        if ($request->isPost()) {
            $params = $request->param();
            unset($params['__token__']);
            $arr = var_export($params, true);
            $url = URL_RELOAD;
            $result = $this->config_set($arr, 'companyRules');
            return $result ? success('添加成功', $url) : error();
        }
        return $this->fetch();
    }

    /**
     * 修改扩展配置文件.
     *
     * @param array $arr 需要更新或添加的配置
     * @param string $file 配置文件名(不需要后辍)
     *
     * @return bool
     */
    function config_set($arr = [], $file = 'dome')
    {
        // 文件路径
        $filepath = Env::get('config_path') . $file . '.php';
        // 检测是否存在,不存在新建
        if (!file_exists($filepath)) {
            $conf = '<?php return [];';
            file_put_contents($filepath, $conf);
        }
        // 添加配置项
        $conf = include $filepath;


        // 修改配置项
        $str = "<?php\r\nreturn \r\n ";
        $str .= $arr;
        $str .= "\r\n;";
        // 写入文件
        return file_put_contents($filepath, $str);

    }

}
